package com.whfc.hdc.service.impl;

import com.whfc.common.exception.BizException;
import com.whfc.common.result.ResultEnum;
import com.whfc.hdc.dao.AlgDeviceConfigMapper;
import com.whfc.hdc.dao.AlgDeviceDataMapper;
import com.whfc.hdc.entity.AlgDeviceConfig;
import com.whfc.hdc.entity.AlgDeviceData;
import com.whfc.hdc.enums.AlgConfigCode;
import com.whfc.hdc.params.AlgDeviceConfigParam;
import com.whfc.hdc.service.AlgDeviceConfigService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author qzexing
 * @version 1.0
 * @date 2021-07-19 17:16
 */
@DubboService(interfaceClass = AlgDeviceConfigService.class, version = "1.0.0")
public class AlgDeviceConfigServiceImpl implements AlgDeviceConfigService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AlgDeviceConfigMapper algDeviceConfigMapper;

    @Autowired
    private AlgDeviceDataMapper algDeviceDataMapper;


    @Override
    public List<String> getConfig(String sn, AlgConfigCode configCode) throws BizException {
        logger.info("获取算法盒子配置信息，sn:{}, configCode:{}", sn, configCode);
        //参数校验
        if (StringUtils.isBlank(sn) || configCode == null) {
            return new ArrayList<>();
        }
        //获取算法盒子配置信息
        return algDeviceConfigMapper.selectConfigList(sn, configCode.getCode());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setConfig(AlgDeviceConfigParam params) throws BizException {
        logger.info("设置算法盒子配置信息，params:{}", params);
        String sn = params.getSn();
        //检测sn
        AlgDeviceData deviceData = algDeviceDataMapper.selectBySn(sn);
        if (deviceData == null) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "该设备不存在");
        }
        AlgConfigCode configCode = AlgConfigCode.parseValue(params.getConfigCode());
        //检测配置编码
        if (configCode == null) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "该配置编码不存在");
        }

        List<String> configList = params.getConfigList();
        //删除旧的配置
        algDeviceConfigMapper.logicDelBySnAndConfigCode(sn, configCode.getCode());
        //保存新的配置
        for (String config : configList) {
            AlgDeviceConfig algDeviceConfig = new AlgDeviceConfig();
            algDeviceConfig.setSn(sn);
            algDeviceConfig.setConfigCode(configCode.getCode());
            algDeviceConfig.setConfigValue(config);
            algDeviceConfigMapper.insertSelective(algDeviceConfig);
        }
    }

}
